<?php
namespace Permission\Model;
use Think\Model;
/**
 * huhaiqin,2023.03.28
 * 权限角色管理
 */
class PermissionRoleModel extends Model{
    
    /**
     * huhaiqin，2023.03.30
     * 检测权限
     * param $check_role string 检测角色
     */
    private function _check_auth($check_role = 'admin'){
        if(!$_SESSION['loginUser']){
            _apiReturn(0,'请先登录~');
        }
        if($check_role == 'admin'){
            if($_SESSION['loginUser']['role'] != 'admin'){
                _apiReturn(0,'您没有权限执行该操作~');
            }
        }
    }

    /**
     * huhaiqin,2023.03.30
     * 添加、编辑角色
     */
    public function _edit($post=[]){
        $this->_check_auth(); //检测权限
        if($post['name'] == ''){
            _apiReturn(0,'角色名不能为空~');
        }
        $post['update_time'] = time();
        $data = $this->create($post);
        if($data['id']){
            if($this->save($data)){
                _apiReturn(1,'success');
            }else{
                _apiReturn(0,'error~');
            }
        }else{
            $data['create_time'] = time();
            $data['id'] = $this->add($data);
            if($data['id']){
                _apiReturn(1,'success');
            }else{
                _apiReturn(0,'error~');
            }
        }
    }

    /**
     * huhaiqin,2023.03.30
     * 数据列表接口
     * param $p int 当前页码
     * param $row int 一页记录数
     * param $query string 查询的sql语句
     */
    public function _query($p = 1 , $row = 10 , $query = ''){
        $sql = "SELECT A.* FROM mini_permission_role A WHERE 1=1 ";
        $sqlcount = "SELECT COUNT(DISTINCT A.`id`) AS tp_count FROM mini_permission_role A WHERE 1=1 ";
        if($query){
            $sql .= $query;
            $sqlcount .= $query;
        }
        //order
        $sql .= " ORDER BY A.listorder asc,A.id desc";
        $sql .= " LIMIT ".($p-1) * $row.",".$row;
        $data['data'] = $this->query($sql);       
        $total = $this->query($sqlcount);
        $data['page']['total'] = $total[0]['tp_count'];
        //处理删除最后一条数据的时候没有数据的bug,请求最后一页没有数据的bug
        if($data['page']['total']>0){
            if (floor(($data['page']['total'] + $row - 1) / $row) < $p) {
                $p = $p - 1;
            }
        }
        //页数数据
        $data['page']['count'] = (int)(($data['page']['total'] + $row -1) / $row);
        $data['page']['cur'] = $p;
        $data['page']['row'] = $row;
        // $data['sql'] = $sql;
        return $data;
    }


    /**
     * huhaiqin,2023.03.30
     * 删除角色
     */
    public function _del($uid=0,$ids = []){
        $this->_check_auth();
        if(count($ids) == 0){
            _apiReturn(0,'角色ID不能为空~');
        }
        //如果是管理员，则直接放行
        $map['id'] = ['in',$ids];
        if($this->where($map)->delete()){
            _apiReturn(1,'success');
        }else{
            _apiReturn(0,'error');
        }
    }
}